//
//  XHSessionViewController.m
//  Bees
//
//  Created by Xiaohan on 2018/12/21.
//  Copyright © 2018 xiaohan. All rights reserved.
//

#import "XHSessionViewController.h"
#import "BeesNIMSessionConfig.h"
#import "NIMCustomLeftBarView.h"
#import "NIMKitTitleView.h"
#import "NIMBadgeView.h"
#import "IQKeyboardManager.h"
#import "NTESSnapchatAttachment.h"
#import "NTESGalleryViewController.h"
#import "NTESVideoViewController.h"
#import "GroupSettingViewController.h"
@interface XHSessionViewController ()
@property (nonatomic, strong) BeesNIMSessionConfig *session_config;
@property (nonatomic,strong)    UIView *currentSingleSnapView;

@end

@implementation XHSessionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
}

#pragma mark - Cell事件
- (BOOL)onTapCell:(NIMKitEvent *)event
{
    BOOL handled = [super onTapCell:event];
    NSString *eventName = event.eventName;
    if ([eventName isEqualToString:NIMKitEventNameTapContent])
    {
        NIMMessage *message = event.messageModel.message;
        NSDictionary *actions = [self cellActions];
        NSString *value = actions[@(message.messageType)];
        if (value) {
            SEL selector = NSSelectorFromString(value);
            if (selector && [self respondsToSelector:selector]) {
                SuppressPerformSelectorLeakWarning([self performSelector:selector withObject:message]);
                handled = YES;
            }
        }
    }
    else if([eventName isEqualToString:NIMKitEventNameTapLabelLink])
    {
        NSString *link = event.data;
        [self openSafari:link];
        handled = YES;
    }
//    else if([eventName isEqualToString:NIMDemoEventNameOpenSnapPicture])
//    {
//        NIMCustomObject *object = event.messageModel.message.messageObject;
//        NTESSnapchatAttachment *attachment = (NTESSnapchatAttachment *)object.attachment;
//        if(attachment.isFired){
//            return handled;
//        }
//        UIView *sender = event.data;
//        self.currentSingleSnapView = [NTESGalleryViewController alertSingleSnapViewWithMessage:object.message baseView:sender];
//        handled = YES;
//    }
//    else if([eventName isEqualToString:NIMDemoEventNameCloseSnapPicture])
//    {
//        //点击很快的时候可能会触发两次查看，所以这里不管有没有查看过 先强直销毁掉
//        NIMCustomObject *object = event.messageModel.message.messageObject;
//        UIView *senderView = event.data;
//        [senderView dismissPresentedView:YES complete:nil];
//        
//        NTESSnapchatAttachment *attachment = (NTESSnapchatAttachment *)object.attachment;
//        if(attachment.isFired){
//            return handled;
//        }
//        attachment.isFired  = YES;
//        NIMMessage *message = object.message;
//        if ([NTESBundleSetting sharedConfig].autoRemoveSnapMessage) {
//            [[NIMSDK sharedSDK].conversationManager deleteMessage:message];
//            [self uiDeleteMessage:message];
//        }else{
//            [[NIMSDK sharedSDK].conversationManager updateMessage:message forSession:message.session completion:nil];
//            [self uiUpdateMessage:message];
//        }
//        [[NSFileManager defaultManager] removeItemAtPath:attachment.filepath error:nil];
//        self.currentSingleSnapView = nil;
//        handled = YES;
//    }
    else if([eventName isEqualToString:NIMKitEventNameTapRobotLink])
    {
        NSString *link = event.data;
        [self openSafari:link];
        handled = YES;
    }
//    else if([eventName isEqualToString:NIMDemoEventNameOpenRedPacket])
//    {
//        NIMCustomObject *object = event.messageModel.message.messageObject;
//        NTESRedPacketAttachment *attachment = (NTESRedPacketAttachment *)object.attachment;
//        [[NTESRedPacketManager sharedManager] openRedPacket:attachment.redPacketId from:event.messageModel.message.from session:self.session];
//        handled = YES;
//    }
//    else if([eventName isEqualToString:NTESShowRedPacketDetailEvent])
//    {
//        NIMCustomObject *object = event.messageModel.message.messageObject;
//        NTESRedPacketTipAttachment *attachment = (NTESRedPacketTipAttachment *)object.attachment;
//        [[NTESRedPacketManager sharedManager] showRedPacketDetail:attachment.packetId];
//        handled = YES;
//    }
    if (!handled) {
        NSAssert(0, @"invalid event");
    }
    return handled;
}

#pragma mark - Cell Actions
- (void)showImage:(NIMMessage *)message
{
    NIMImageObject *object = message.messageObject;
    NTESGalleryItem *item = [[NTESGalleryItem alloc] init];
    item.thumbPath      = [object thumbPath];
    item.imageURL       = [object url];
    item.name           = [object displayName];
    item.itemId         = [message messageId];
    item.size           = [object size];
    
    NIMSession *session = [self isMemberOfClass:[XHSessionViewController class]]? self.session : nil;
    
    NTESGalleryViewController *vc = [[NTESGalleryViewController alloc] initWithItem:item session:session];
    [self.navigationController pushViewController:vc animated:YES];
    if(![[NSFileManager defaultManager] fileExistsAtPath:object.thumbPath]){
        //如果缩略图下跪了，点进看大图的时候再去下一把缩略图
        __weak typeof(self) wself = self;
        [[NIMSDK sharedSDK].resourceManager download:object.thumbUrl filepath:object.thumbPath progress:nil completion:^(NSError *error) {
            if (!error) {
                [wself uiUpdateMessage:message];
            }
        }];
    }
}

- (void)showVideo:(NIMMessage *)message
{
    NIMVideoObject *object = message.messageObject;
    NIMSession *session = [self isMemberOfClass:[XHSessionViewController class]]? self.session : nil;
    
    NTESVideoViewItem *item = [[NTESVideoViewItem alloc] init];
    item.path = object.path;
    item.url  = object.url;
    item.session = session;
    item.itemId  = object.message.messageId;
    
    NTESVideoViewController *playerViewController = [[NTESVideoViewController alloc] initWithVideoViewItem:item];
    [self.navigationController pushViewController:playerViewController animated:YES];
    if(![[NSFileManager defaultManager] fileExistsAtPath:object.coverPath]){
        //如果封面图下跪了，点进视频的时候再去下一把封面图
        __weak typeof(self) wself = self;
        [[NIMSDK sharedSDK].resourceManager download:object.coverUrl filepath:object.coverPath progress:nil completion:^(NSError *error) {
            if (!error) {
                [wself uiUpdateMessage:message];
            }
        }];
    }
}

- (void)openSafari:(NSString *)link
{
    NSURLComponents *components = [[NSURLComponents alloc] initWithString:link];
    if (components)
    {
        if (!components.scheme)
        {
            //默认添加 http
            components.scheme = @"http";
        }
        [[UIApplication sharedApplication] openURL:[components URL]];
    }
}
- (NSDictionary *)cellActions
{
    static NSDictionary *actions = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        actions = @{@(NIMMessageTypeImage) :    @"showImage:",
                    @(NIMMessageTypeVideo) :    @"showVideo:",
                    @(NIMMessageTypeLocation) : @"showLocation:",
                    @(NIMMessageTypeFile)  :    @"showFile:",
                    @(NIMMessageTypeCustom):    @"showCustom:"};
    });
    return actions;
}
#pragma mark - 自定义UI
- (void)setupUI{
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = UIColorHex(333333);
    self.tableView.contentInset = UIEdgeInsetsMake(kTopHeight, 0, 0, 0);
    [self.view bringSubviewToFront:self.customNavigationBar];
    self.customNavigationBar.backgroundColor = [UIColor blackColor];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = kDefaultFont(17);
    self.subTitleLabel.textColor = [UIColor whiteColor];
    self.subTitleLabel.font = kDefaultFont(17);
    self.StatusBarStyle = UIStatusBarStyleLightContent;
    self.sessionInputView.backgroundColor = UIColorHex(333333);
    self.sessionInputView.toolBar.backgroundColor = UIColorHex(333333);
    self.leftBackImg = @"white_back";
    self.navigationItem.leftItemsSupplementBackButton = NO;
    
    [self addNavigationItemWithImageNames:@[@"group_setting"] isLeft:NO
                                   target:self action:@selector(rightBtnClick) tags:nil];
//    [self setupCustomNav];
}
- (void)rightBtnClick{
    GroupSettingViewController *vc = [[GroupSettingViewController alloc]initWithSession:self.session];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setupCustomNav{
    NIMCustomLeftBarView *leftBarView = [[NIMCustomLeftBarView alloc] init];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBarView];
    if (@available(iOS 11.0, *)) {
        leftBarView.translatesAutoresizingMaskIntoConstraints = NO;
    }
    leftBarView.backgroundColor = [UIColor redColor];
    UIButton *leftBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [leftBackBtn addTapBlock:^(UIButton * _Nonnull btn) {
        [super backBtnClicked];
    }];
    [leftBackBtn setImage:IMAGE_NAMED(@"white_back") forState:UIControlStateNormal];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:leftBackBtn];

    self.navigationItem.leftBarButtonItems = @[backItem,leftItem];
    self.navigationItem.leftItemsSupplementBackButton = NO;
}

- (void)changeLeftBarBadge:(NSInteger)unreadCount
{
//    NIMCustomLeftBarView *leftBarView = (NIMCustomLeftBarView *)[[self.navigationItem.leftBarButtonItems lastObject]customView];
//    leftBarView.badgeView.badgeValue = @(unreadCount).stringValue;
//    leftBarView.badgeView.hidden = !unreadCount;
}


- (id<NIMSessionConfig>)sessionConfig {
    return self.session_config;
}

- (BeesNIMSessionConfig*)session_config{
    if (!_session_config) {
        _session_config = [BeesNIMSessionConfig new];
    }
    return _session_config;
}
@end
